var app = getApp()
var car = require('../../template/car/cakecar.js')
var category = require('../../template/category/cakecategory.js')
var cakebuy = require('../../template/cakebuy/cakebuy.js')
var allCake

Page({
  data: {
    topNeedShow: true,
    cakeLoaded: false,
    scrolltop: 0,
    idflag: '',
    stationId: '',
    cakelist: []
  },

  onLoad: function () {
    app.hideLoading()
    this.idFlag = app.globalData.idFlag || ''
    car.init(this)
    cakebuy.init(this, this.addCarCallBack, this.buyCallBack)
  },

  onShow: function () {
    this.lastAddress = this.data.address
    app.ready(() => {
      if (app.globalData.address == null) {
        app.showAddressModal()
      } else {
        this.handleReady()
      }
    })
    app.error(err => {
      this.dealEmpty()
      app.toast.error(err)
    })
  },

  handleReady: function () {
    this.setData({
      address: app.globalData.address
    })

    let gAddress = app.globalData.address
    let address = this.lastAddress

    if (address && (gAddress.ID !== address.ID || gAddress.ADDRESS !== address.ADDRESS)) {
      app.globalData.needClearCakeCar = '1'
      this.setData({
        cakeLoaded: false
      })
    }

    this.loadCakeList()

    if (this.idFlag) {
      this.setData({
        idflag: this.idFlag
      })
      app.globalData.idFlag = null
    }

    if (app.globalData.tempcar != null) {
      var goodslist = app.globalData.tempcar.list1
      var goodsidlist = app.globalData.tempcar.list2
      car.reset(goodslist, goodsidlist)
      app.globalData.tempcar = null
    }

    if (app.globalData.needClearCakeCar === '1') {
      app.globalData.needClearCakeCar = null
      car.init(this)
    }

    cakebuy.close()
  },
  onShareAppMessage: function () {

  },
  loadCakeList: function () {
    const {CITYID, LOCATION, CITYNAME, COUNTYNAME, ADDRESS} = this.data.address
    var url = `/yuanmai_we/mcake/product/get/${CITYID}`
    var property = {
      location: LOCATION,
      hasAddress: !!ADDRESS,
      city: CITYNAME,
      county: COUNTYNAME,
      address: ADDRESS
    }

    var params = {
      datas: JSON.stringify(property)
    }

    app.get(url, params).then(
      this.cakeListCallBack.bind(this),
      err => this.dealEmpty()
    )

    /*if (!this.data.cakeLoaded) {
      app.showLoading()
    }*/

  },
  dealEmpty: function () {
    this.hideLoading()
    this.setData({
      cakelist: [],
      cakeLoaded: true
    })
    app.confirm('当前地区没有商品可销售，是否去修改地址?', '是', '否').then(confirm => {
      if (confirm) {
        wx.navigateTo({
          url: '/pages/my/address/address?type=select'
        })
      }
    })
  },
  cakeListCallBack: function (res) {
    //app.hideLoading()
    this.hideLoading()

    if (!res.data || !res.data.products || res.data.products.length === 0) {
      this.dealEmpty()
      return
    }

    var products = res.data.products.list
    var cakelist = []

    if (this.idFlag) {
      app.globalData.idFlag = null
    } else {
      if (this.data.cakelist.length !== products.length) {
        this.data.scrolltop = 0
      }
    }

    for (var i = 0; i < products.length; i++) {
      var cakeinfo = {}
      cakeinfo.goodsid = products[i].id
      cakeinfo.name = products[i].name
      if (products[i].french != null && products[i].french !== undefined) {
        cakeinfo.fullname = cakeinfo.name + ' ' + products[i].french
      }
      else {
        cakeinfo.fullname = cakeinfo.name
      }
      if (products[i].fname != null && products[i].fname !== undefined) {
        cakeinfo.specs = products[i].fname.split(',')
      }
      else {
        cakeinfo.specs = []
      }
      if (products[i].fid != null && products[i].fid !== undefined) {
        cakeinfo.fid = products[i].fid
      }
      else {
        cakeinfo.fid = ''
      }
      cakeinfo.img = products[i].limg
      cakeinfo.icon = products[i].img
      cakeinfo.price = products[i].price
      cakeinfo.intro = products[i].chineseBrief
      cakeinfo.weight = products[i].spec
      cakeinfo.list = products[i].list
      cakelist.push(cakeinfo)
    }

    this.setData({
      mid: res.data.mid,
      fid: res.data.fid,
      stationId: res.data.stationId,
      cakelist: cakelist,
      idflag: this.idFlag,
      cakeLoaded: true
    })

    allCake = cakelist

    var cgritems = res.data.flavorList || []
    cgritems.unshift({name: '全部', id: '0'})
    category.init(this, cgritems, this.categoryChooseCallBack)

  },
  hideLoading: function () {
    this.selectComponent('#spin').hide()
  },
  buyCake: function (e) {
    var goodsindex = e.currentTarget.dataset.goodsindex
    cakebuy.show(goodsindex)
  },
  addressHandle: function () {
    if (this.data.goodslist.length > 0) {
      app.confirm('切换地址可能导致购物车中部分商品无效，是否继续？', '是', '否').then(confirm => {
        if (confirm) {
          wx.navigateTo({
            url: '/pages/my/address/address?type=select'
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/my/address/address?type=select'
      })
    }
  },

  showCar: car.showCar,
  submitOrder: car.submitOrder,
  closeCar: car.closeCar,
  toggleCar: car.toggleCar,
  handleCount: car.handleCount,

  showCategory: category.show,
  closeCategory: category.close,
  toggleCategory: category.toggle,
  chooseCategory: category.choose,

  chooseSpec: cakebuy.chooseSpec,
  closeCakeBuy: cakebuy.close,
  addCarAction: cakebuy.addCar,
  buyAction: cakebuy.buy,

  goodsScroll: function (e) {
    var topNeedShow = true
    if (e.detail.deltaY < 0 && e.detail.scrollTop > 20) {
      topNeedShow = false
    }
    if (this.data.cgr_show === true) {
      topNeedShow = true
    }
    if (this.data.topNeedShow !== topNeedShow) {
      this.setData({
        topNeedShow: topNeedShow
      })
    }
  },

  categoryChooseCallBack: function (category_code) {
    if (category_code.id.toString() === '0') {
      this.setData({
        cakelist: allCake
      })
    }
    else {
      var cakelist = []
      for (var i = 0; i < allCake.length; i++) {
        var fidArr = allCake[i].fid.split(',')
        if (fidArr.indexOf(category_code.id.toString()) >= 0) {
          cakelist.push(allCake[i])
        }
      }
      for (var i = 0; i < allCake.length; i++) {
        if (cakelist.indexOf(allCake[i]) < 0) {
          cakelist.push(allCake[i])
        }
      }
      this.setData({
        scrolltop: 0,
        cakelist: cakelist
      })
    }
    category.close()
  },
  addCarCallBack: function (goods = null) {
    var goodsinfo
    var num = 0
    var specindex = -1
    if (goods == null) {
      goodsinfo = this.data.cakelist[this.data.goodsindex]
      num = 1
      specindex = this.data.curspec
    }
    else {
      goodsinfo = goods.goods
      num = goods.num
      specindex = goods.curspec
    }

    var small_img = goodsinfo.list[specindex].pic.url + goodsinfo.list[specindex].pic.list[0].s
    var nameSpec = goodsinfo.name + ' ' + goodsinfo.list[specindex].spec
    var data = {
      options: '1',
      goodsid: goodsinfo.list[specindex].id,
      price: goodsinfo.list[specindex].price,
      sku: goodsinfo.list[specindex].sku,
      spec: goodsinfo.list[specindex].spec,
      size: goodsinfo.list[specindex].size,
      tips: goodsinfo.list[specindex].edible,
      name: nameSpec,
      shortname: goodsinfo.name,
      img: goodsinfo.img,
      icon: goodsinfo.icon,
      image: small_img,
      num: num
    }

    car.handleCount(data)
  },
  buyCallBack: function () {
    if (this.data.address == null || this.data.address === undefined) {
      app.toast.error('请先添加收货地址！')
      return
    }
    var goodsinfo = this.data.cakelist[this.data.goodsindex]
    var small_img = goodsinfo.list[this.data.curspec].pic.url + goodsinfo.list[this.data.curspec].pic.list[0].s
    var nameSpec = goodsinfo.name + ' ' + goodsinfo.list[this.data.curspec].spec
    var goods = {
      goodsid: goodsinfo.list[this.data.curspec].id,
      ID: goodsinfo.list[this.data.curspec].id,
      price: goodsinfo.list[this.data.curspec].price,
      sku: goodsinfo.list[this.data.curspec].sku,
      spec: goodsinfo.list[this.data.curspec].spec,
      size: goodsinfo.list[this.data.curspec].size,
      tips: goodsinfo.list[this.data.curspec].edible,
      name: nameSpec,
      shortname: goodsinfo.name,
      img: goodsinfo.img,
      icon: goodsinfo.icon,
      image: small_img,
      num: '1'
    }

    var orderinfo = {
      mid: this.data.mid,
      fid: this.data.fid,
      stationId: this.data.stationId,
      goodslist: [goods]
    }

    var urlstr = '../neworder/neworder?type=cake&orderinfo=' +
      encodeURIComponent(JSON.stringify(orderinfo)) +
      '&address=' +
      encodeURIComponent(JSON.stringify(this.data.address))

    wx.navigateTo({
      url: urlstr
    })
  },
  toPageTop: function () {
    this.setData({
      scrolltop: 0
    })
  },
  cakeDetail: function (e) {
    app.globalData.tempcar = {
      list1: this.data.goodslist,
      list2: this.data.goodsidlist
    }
    var indexval = e.currentTarget.dataset.goodsindex
    var goodsid = this.data.cakelist[indexval].goodsid
    wx.navigateTo({
      url: `./cakedetail/cakedetail?goodsid=${goodsid}`
    })
  }
})
